﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Infrastructure.EFCore.Share.Extensions;
using Windows.Infrastructure.Share.CustomException;
using Windows.Infrastructure.Share.Extensions;

namespace Windows.Admin.Service
{
    public class OrganizationService : IOrganizationService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly AdminDbContext _db;
        public OrganizationService(IMapper mapper, AdminDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取组织机构列表基础数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrganizationResponse>> GetBasicOrganizations()
        {
            var list = await _db.Organization.ToListAsync();
            return _mapper.Map<List<OrganizationResponse>>(list);
        }
        /// <summary>
        /// 组织机构视图
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrganizationResponse>> Query()
        {
            var list = await _db.Organization.ToListAsync();
            return _mapper.Map<List<OrganizationResponse>>(list);
        }
        /// <summary>
        /// 获取id的组织机构详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<OrganizationResponse> Detail(int id)
        {
            var model = await _db.Organization.FindByIdAsync(id);
            return _mapper.Map<OrganizationResponse>(model);
        }
        /// <summary>
        /// 组织机构保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(OrganizationSaveRequest request)
        {
            if (await _db.Organization.AnyAsync(x => x.Name.ToLower() == request.Name && x.PId == request.PId && x.Id != request.Id))
                throw new ApiException("组织机构名称已存在!");
            Organization model = _mapper.Map<Organization>(request);
            
            if (request.Id != null)
            {
                 model = await _db.Organization.FindByIdAsync(request.Id.Value) ?? throw new ApiException("组织机构不存在!");
                model.PId = request.PId;
                model.Code = request.Code;
                model.Name = request.Name;
                model.Telephone = request.Telephone;
                model.Fax = request.Fax;
                model.Email = request.Email;
                model.Sort = request.Sort;
                model.Remark = request.Remark;
            }
            if (request.PId != null)
            {
                Organization? parent = await _db.Organization.FindByIdAsync(request.PId.Value);
                if (parent != null)
                {
                    if (parent.Level.IsNullOrEmpty())
                        model.Level = parent.Id + "";
                    else
                        model.Level = parent.Level + "," + parent.Id;
                }
            }
            if (request.Id == null)
                await _db.Organization.AddAsync(model);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 组织机构删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task Remove(long id)
        {
            var model = await _db.Organization.FindByIdAsync(id) ?? throw new ApiException("组织机构不存在!");
            var any = await _db.Organization.Include(x => x.Organization_Employees).Where(x => (x.Level != null && ("," + x.Level + ",").Contains("," + id + ",") || x.Id == id) && x.Organization_Employees.Count > 0).AnyAsync();
            if (any)
            {
                throw new ApiException("组织机构已分配员工,不允许删除!");
            }
            var list = await _db.Organization.Where(x => x.Level != null && ("," + x.Level + ",").Contains("," + id + ",")).ToListAsync();
            if (list.Count > 0)
            {
                foreach (var l in list)
                {
                    l.IsEnable = false;
                }
            }
            model.IsEnable = false;
            await _db.SaveChangesAsync();
        }
    }
}
